package com.axin.oss.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.axin.common.core.constant.CacheConstants;
import com.axin.common.core.domain.web.TableDataInfo;
import com.axin.common.core.exception.ServiceException;
import com.axin.common.mybatis.core.ServicePlusImpl;
import com.axin.common.mybatis.page.PagePlus;
import com.axin.common.mybatis.utils.PageUtils;
import com.axin.common.redis.utils.RedisUtils;
import com.axin.common.redis.utils.RedisUtilss;
import com.axin.oss.api.domain.SysOssConfig;
import com.axin.oss.api.dto.SysOssConfigDTO;
import com.axin.oss.api.vo.SysOssConfigVo;
import com.axin.oss.mapper.SysOssConfigMapper;
import com.axin.oss.service.ISysOssConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 对象存储配置Service业务层处理
 *
 * @Author axin
 * @Date 2021/11/3 22:22
 **/
@Slf4j
@Service
public class SysOssConfigServiceImpl extends ServicePlusImpl<SysOssConfigMapper, SysOssConfig, SysOssConfigVo> implements ISysOssConfigService {

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 项目启动时，初始化参数到缓存，加载配置类
     */
    @PostConstruct
    public void init() {
        List<SysOssConfig> list = list();
        for (SysOssConfig config : list) {
            String configKey = config.getConfigKey();
            if ("1".equals(config.getStatus())) {
                RedisUtilss.setCacheObject(CacheConstants.CACHE_CONFIG_KEY, configKey);
            }
            setConfigCache(true, config);
        }
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public TableDataInfo<SysOssConfigVo> queryPageList(SysOssConfigDTO dto) {
        PagePlus<SysOssConfig, SysOssConfigVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(dto));
        return PageUtils.buildDataInfo(result);
    }

    private LambdaQueryWrapper<SysOssConfig> buildQueryWrapper(SysOssConfigDTO dto) {
        LambdaQueryWrapper<SysOssConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(dto.getConfigKey()), SysOssConfig::getConfigKey, dto.getConfigKey());
        lqw.like(StringUtils.isNotBlank(dto.getBucketName()), SysOssConfig::getBucketName, dto.getBucketName());
        lqw.eq(StringUtils.isNotBlank(dto.getStatus()), SysOssConfig::getStatus, dto.getStatus());
        return lqw;
    }

    @Override
    public SysOssConfigVo queryById(Long ossConfigId){
        return getVoById(ossConfigId);
    }


    @Override
    public Boolean insertByDTO(SysOssConfigDTO dto) {
        SysOssConfig config = BeanUtil.toBean(dto, SysOssConfig.class);
        validEntityBeforeSave(config);
        return setConfigCache(save(config), config);
    }


    @Override
    public Boolean updateByDTO(SysOssConfigDTO dto) {
        SysOssConfig config = BeanUtil.toBean(dto, SysOssConfig.class);
        validEntityBeforeSave(config);
        LambdaUpdateWrapper<SysOssConfig> luw = new LambdaUpdateWrapper<>();
        luw.set(StringUtils.isBlank(config.getPrefix()), SysOssConfig::getPrefix, "");
        luw.set(StringUtils.isBlank(config.getRegion()), SysOssConfig::getRegion, "");
        luw.eq(SysOssConfig::getOssConfigId, config.getOssConfigId());
        return setConfigCache(update(config, luw), config);
    }


    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {

        List<SysOssConfig> list = new ArrayList();
        for (Long configId : ids) {
            SysOssConfig config = getById(configId);
            list.add(config);
        }
        boolean flag = removeByIds(ids);
        if (flag) {
            list.stream().forEach(sysOssConfig -> {
                redisUtils.delete(getCacheKey(sysOssConfig.getConfigKey()));
            });
        }
        return flag;

    }


    /**
     * 启用禁用状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOssConfigStatus(SysOssConfigDTO dto) {
        SysOssConfig sysOssConfig = BeanUtil.toBean(dto, SysOssConfig.class);
        int row = baseMapper.update(null, new LambdaUpdateWrapper<SysOssConfig>()
                .set(SysOssConfig::getStatus, "0"));
        row += baseMapper.updateById(sysOssConfig);
        if (row > 0) {
            redisUtils.set(CacheConstants.CACHE_CONFIG_KEY, sysOssConfig.getConfigKey());
        }
        return row;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_OSS_KEY + configKey;
    }


    /**
     * 如果操作成功 则更新缓存
     * @param flag 操作状态
     * @param config 配置
     * @return 返回操作状态
     */
    private boolean setConfigCache(boolean flag, SysOssConfig config) {
        if (flag) {
            RedisUtilss.setCacheObject(getCacheKey(config.getConfigKey()), JSONObject.toJSONString(config));
            RedisUtilss.publish(CacheConstants.CACHE_CONFIG_KEY, config.getConfigKey(), msg -> {
                log.info("发布刷新OSS配置 => " + msg);
            });
        }
        return flag;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysOssConfig entity){
        if (!checkConfigKeyUnique(entity)) {
            throw new ServiceException("操作配置'" + entity.getConfigKey() + "'失败, 配置key已存在!");
        }
    }

    /**
     * 判断configKey是否唯一
     */
    private boolean checkConfigKeyUnique(SysOssConfig sysOssConfig) {

        long ossConfigId = ObjectUtil.isNull(sysOssConfig.getOssConfigId()) ? -1L : sysOssConfig.getOssConfigId();
        SysOssConfig info = getOne(new LambdaQueryWrapper<SysOssConfig>()
                .select(SysOssConfig::getOssConfigId, SysOssConfig::getConfigKey)
                .eq(SysOssConfig::getConfigKey, sysOssConfig.getConfigKey()));
        if (ObjectUtil.isNotNull(info) && info.getOssConfigId() != ossConfigId) {
            return false;
        }
        return true;
    }
}
